package com.gitee.wsl.compose.base

import androidx.compose.foundation.shape.GenericShape
import androidx.compose.runtime.Immutable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.LayoutDirection

/**
 * Model for drawing title with shape for crop selection menu. Aspect ratio is used
 * for setting overlay in state and UI
 */
@Immutable
data class CropAspectRatio(
    val title: String,
    val shape: Shape,
    val aspectRatio: AspectRatio = AspectRatio.Original,
    val icons: List<Int> = listOf()
)

/**
 * Value class for containing aspect ratio
 * and [AspectRatio.Original] for comparing
 */
@Immutable
data class AspectRatio(val value: Float) {
    companion object {
        val Original = AspectRatio(-1f)
    }
}

/**
 * Aspect ratio list with pre-defined aspect ratios
 */
val aspectRatios = listOf(
    CropAspectRatio(
        title = "9:16",
        shape = createRectShape(AspectRatio(9 / 16f)),
        aspectRatio = AspectRatio(9 / 16f)
    ),
    CropAspectRatio(
        title = "2:3",
        shape = createRectShape(AspectRatio(2 / 3f)),
        aspectRatio = AspectRatio(2 / 3f)
    ),
    CropAspectRatio(
        title = "Original",
        shape = createRectShape(AspectRatio.Original),
        aspectRatio = AspectRatio.Original
    ),
    CropAspectRatio(
        title = "1:1",
        shape = createRectShape(AspectRatio(1 / 1f)),
        aspectRatio = AspectRatio(1 / 1f)
    ),
    CropAspectRatio(
        title = "16:9",
        shape = createRectShape(AspectRatio(16 / 9f)),
        aspectRatio = AspectRatio(16 / 9f)
    ),
    CropAspectRatio(
        title = "1.91:1",
        shape = createRectShape(AspectRatio(1.91f / 1f)),
        aspectRatio = AspectRatio(1.91f / 1f)
    ),
    CropAspectRatio(
        title = "3:2",
        shape = createRectShape(AspectRatio(3 / 2f)),
        aspectRatio = AspectRatio(3 / 2f)
    ),
    CropAspectRatio(
        title = "3:4",
        shape = createRectShape(AspectRatio(3 / 4f)),
        aspectRatio = AspectRatio(3 / 4f)
    ),
    CropAspectRatio(
        title = "3:5",
        shape = createRectShape(AspectRatio(3 / 5f)),
        aspectRatio = AspectRatio(3 / 5f)
    )
)


/**
 * Creates a [Rect] shape with given aspect ratio.
 */
fun createRectShape(aspectRatio: AspectRatio): GenericShape {
    return GenericShape { size: Size, _: LayoutDirection ->
        val value = aspectRatio.value

        val width = size.width
        val height = size.height
        val shapeSize =
            if (aspectRatio == AspectRatio.Original) Size(width, height)
            else if (value > 1) Size(width = width, height = width / value)
            else Size(width = height * value, height = height)

        addRect(Rect(offset = Offset.Zero, size = shapeSize))
    }
}
